// pages/site/addsite/index.js
const app = getApp() // 引入app
const _request = require("../../../utils/request.js"); // 引入require
// 引入SDK核心类，js文件根据自己业务，位置可自行放置
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk
const area = require('../../../utils/area');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl, //全局img路径
    city: '省、市、区',
    GDId: [],
    show: false,
    areaList: area.areaList,
    location: '',
    storeLocation: null,
    getArea: [],
    province: null,
    citydata: null,
    district: null,
    latitude: '',
    longitude: '',
  },


  // 展示选择城市
  showmolde() {
    // this.setData({
    //   show: true
    // });
  },

  // 关闭选择城市
  onClose() {
    this.setData({
      show: false
    });
  },

  // 获取省市区id
  getArea(area, city, district) {
    this.data.getArea.map(item => {
      if (item.name == area && item.name != '北京市') {
        this.setData({
          province: item
        })
        item.areaList.map(item => {
          if (item.name == city) {
            this.setData({
              citydata: item
            })
            item.areaList.map(item => {
              if (item.name == district) {
                this.setData({
                  district: item
                })
              }
            })
          }
        })
      } else if (item.name == area && item.name == '北京市') {
        this.setData({
          province: item
        })
        this.setData({
          citydata: item.areaList[0]
        })
        item.areaList[0].areaList.map(item => {
          if (item.name == district) {
            this.setData({
              district: item
            })
          }
        })
      }
    })
  },

  // 完成选择城市，发送请求
  onFirm(e) {
    this.setData({
      show: false,
      city: e.detail.values.map(item => {
        return item.name
      }),
      GDId: e.detail.values.map(item => {
        return item.code
      })
    });
    this.setData({
      cityGDId: this.data.GDId[1],
      districtGDId: this.data.GDId[2],
      provinceGDId: this.data.GDId[0]
    })
    console.log(e);
  },

  // 获取用户定位
  getUserLocation() {
    console.log('定位');
    let vm = this
    wx.getSetting({
      success(res) {
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 2000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 2000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 2000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          // 不存在就获取权限
          vm.getLocation()
        } else {
          //调用wx.getLocation的API
          vm.getLocation()
        }
      }
    })
  },
  // 授权定位权限
  getLocation() {
    var _this = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude;
        let longitude = res.longitude;
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
          key: 'MBEBZ-6VQCP-EYSDK-LT7FQ-2LNUS-G4BTN'
        });
        // 经纬度转城市
        qqmapsdk.reverseGeocoder({
          //位置坐标
          location: {
            latitude: latitude,
            longitude: longitude
          },

          //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
          success: function (res) { //成功后的回调
            console.log(res, 'res');
            var res = res.result;
            var mks = [];
            mks.push({ // 获取返回结果，放到mks数组中
              title: res.address,
              id: 0,
              latitude: res.location.lat,
              longitude: res.location.lng,
              iconPath: './resources/placeholder.png', //图标路径
              width: 20,
              height: 20,
              callout: { //在markers上展示地址名称，根据需求是否需要
                content: res.address,
                color: '#000',
                display: 'ALWAYS'
              },
              ad_info: res.ad_info,
              address_component: res.address_component,
            });
            _this.getArea(res.ad_info.province, res.ad_info.city, res.ad_info.district)
            _this.setData({ //设置markers属性和地图位置poi，将结果在地图展示
              markers: mks,
              city: res.ad_info.province + ',' + res.ad_info.city + ',' + res.ad_info.district,
              latitude: res.location.lat,
              longitude: res.location.lng,
            });
          },
          fail: function (error) {
            console.error(error);
          },
          complete: function (res) {}
        })
        // 储存地址
        wx.setStorageSync('location', res)
      },
      fail: function (error) {
        console.log(error, 'error');
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow() {
    // 获取区域
    _request.get('/area/getArea', {}).then((res) => {
      this.setData({
        getArea: res.data.data
      })
    }).catch((error) => {
      console.log(error, 'error');
    })
  },
  onAdd: function () {
    const {
      location,
      province,
      citydata,
      district,
      latitude,
      longitude,
      city
    } = this.data
  console.log(this.data);
    const pages = getCurrentPages(); //获取页面栈堆
    const prev = pages[pages.length - 2]; //-2即为父级页面，想跳两层的话就-3
    prev.setData({ //用setData()的特性给父级页面赋值并重新渲染
      location,
      province,
      citydata,
      district,
      latitude,
      longitude,
      city
    })
    wx.navigateBack({
      delta: 1
    })
  }
})